import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.dates as mdates

# 1. 读取并排序
df = pd.read_excel("Monthly_Indices_Full.xlsx", parse_dates=["Month"])
df = df.sort_values("Month")

# 2. 全局字体设置为 Times New Roman
plt.rcParams['font.family'] = 'serif'
plt.rcParams['font.serif'] = ['Times New Roman']

# 3. 公共参数
start_base = pd.Timestamp("2014-01-01")
end_base = df["Month"].max()
bar_width = pd.Timedelta(days=20)  # 用于左右缓冲

# 4. 指标与配色
indices = {
    "BalanceIndex": "#1f77b4",  # 蓝
    "ImpactIndex": "#ff7f0e",  # 橙
    "ToneIndex": "#2ca02c"  # 绿
}

# 5. 循环绘图
for idx, color in indices.items():
    fig, ax = plt.subplots(figsize=(12, 6))

    # 折线图
    ax.plot(
        df["Month"], df[idx],
        color=color, linewidth=2, marker='o',
        label=idx
    )

    # 首尾缓冲，确保首尾数据点不被挤出画布
    start = start_base - bar_width / 1
    end = end_base + bar_width / 1
    ax.set_xlim(start, end)

    # 刻度：每隔 4 个月打主刻度（1,5,9 月），每月打次刻度
    major = mdates.MonthLocator(bymonth=range(1, 13, 4))
    minor = mdates.MonthLocator()
    fmt = mdates.DateFormatter('%Y-%m')
    ax.xaxis.set_major_locator(major)
    ax.xaxis.set_major_formatter(fmt)
    ax.xaxis.set_minor_locator(minor)
    plt.setp(ax.get_xticklabels(), rotation=45, ha='right')

    # 网格：横纵主刻度网格
    ax.grid(which='major', axis='both', linestyle='--', linewidth=0.5)

    # 标签、图例、标题
    ax.set_xlabel("Month")
    ax.set_ylabel(idx, color=color)
    ax.legend(loc='upper left')
    # plt.title(f"{idx} ")

    plt.tight_layout()
    filename = f"{idx}.jpg"
    fig.savefig(filename, format='jpg', dpi=300)
    plt.show()
